package com.bruip.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bruip.reggie.common.BaseResponse;
import com.bruip.reggie.dto.DishDto;
import com.bruip.reggie.pojo.Category;
import com.bruip.reggie.pojo.Dish;
import com.bruip.reggie.pojo.DishFlavor;
import com.bruip.reggie.service.CategoryService;
import com.bruip.reggie.service.DishFlavorService;
import com.bruip.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 王若龙
 * @date 2022-10-06 18:56
 */
@RestController
@Slf4j
@Api("菜品相关的请求")
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("处理分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示的条数", required = true),
            @ApiImplicitParam(name = "name", value = "菜品名称，条件查询", required = false)
    })
    @GetMapping("/page")
    public BaseResponse<Page> getPage(int page, int pageSize, String name) {
        Page<DishDto> dishDtoPage = null;
//        //查询缓存
//        String key = "dish:page:" + page + "_" + pageSize + "_" + name;
//        dishDtoPage = (Page<DishDto>) redisTemplate.opsForValue().get(key);
//        if (dishDtoPage != null){
//            return BaseResponse.success(dishDtoPage);
//        }

        Page<Dish> dishPage = new Page<>(page, pageSize);
        dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByAsc(Dish::getCategoryId);
        dishService.page(dishPage, queryWrapper);
        /*
           以下代码
           给菜品列表中的类别名称赋值
         */
        //对象拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map(item -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        // 缓存中不存在的情况下，查询数据库后，加入缓存
//        redisTemplate.opsForValue().set(key, dishDtoPage, 30, TimeUnit.MINUTES);
        return BaseResponse.success(dishDtoPage);
    }

    /**
     * 新增菜品
     *
     * @param dishDto 菜品dto
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping
    public BaseResponse<String> saveDish(@RequestBody DishDto dishDto) {
        dishService.saveDishAndDishFlavor(dishDto);
        //清理缓存中该类别的菜品信息
        Set<String> keys = redisTemplate.keys("dish:" + dishDto.getCategoryId().toString() + "_*");
        redisTemplate.delete(keys);
        return BaseResponse.success("新增菜品成功");
    }

    /**
     * 得到菜信息更新页面
     *
     * @param id id
     * @return {@link BaseResponse}<{@link DishDto}>
     */
    @GetMapping("/{id}")
    public BaseResponse<DishDto> updatePageGetDishInfo(@PathVariable("id") Long id) {
        DishDto flavor = dishService.getByIdWithFlavor(id);
        return BaseResponse.success(flavor);
    }

    /**
     * 更新菜品
     *
     * @param dishDto 菜dto
     * @return {@link BaseResponse}<{@link String}>
     */
    @PutMapping
    public BaseResponse<String> updateDish(@RequestBody DishDto dishDto) {
        log.info("保存修改后的信息");
        dishService.updateDishAndDishFlavor(dishDto);
        //清理缓存中该类别的菜品信息
        Set<String> keys = redisTemplate.keys("dish:*" + dishDto.getCategoryId().toString() + "_*");
        redisTemplate.delete(keys);

        return BaseResponse.success("菜品修改成功");
    }

    /**
     * 根据条件，查询对应的菜品类别及对应菜品
     *
     * @param dish
     * @return {@link BaseResponse}<{@link List}<{@link Dish}>>
     */
    @GetMapping("/list")
    public BaseResponse<List<DishDto>> dishList(Dish dish) {
        List<DishDto> list = null;
        String key = "dish:list:" + dish.getCategoryId() + ":" + dish.getStatus();
        //查询缓存，
        list = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (list != null) {
            //如果存在数据，则直接返回
            return BaseResponse.success(list);
        }
        // 不存在

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //只查询起售状态的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);

        List<Dish> dishList = dishService.list(queryWrapper);

        list = dishList.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //否则，查询数据库，将值存入缓存后，返回给页面
        redisTemplate.opsForValue().set(key, list, 1, TimeUnit.HOURS);

        return BaseResponse.success(list);
    }
//    @GetMapping("/list")
//    public BaseResponse<List<Dish>> dishList(Dish dish){
//        //条件构造器
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        //添加条件
//        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        //只查询起售状态的菜品
//        queryWrapper.eq(Dish::getStatus, 1);
//        //添加排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);
//
//        List<Dish> dishList = dishService.list(queryWrapper);
//
//        return BaseResponse.success(dishList);
//    }

    /**
     * 设置状态
     *
     * @param ids    id
     * @param status 状态
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping("/status/{status}")
    public BaseResponse<String> setStatus(@RequestParam List<Long> ids, @PathVariable("status") Integer status) {
        LambdaUpdateWrapper<Dish> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        queryWrapper.set(Dish::getStatus, status);
        dishService.update(queryWrapper);

        //清理缓存中的菜品信息
        Set<String> keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);

        return BaseResponse.success("状态修改成功");
    }

    @DeleteMapping
    public BaseResponse<String> delete(@RequestParam List<Long> ids) {
        dishService.removeWithFlavor(ids);
        //清理缓存中的菜品信息
        Set<String> keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);
        return BaseResponse.success("删除菜品成功");

    }

}
